package com.example.common.mvvm.viewmodel;

import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.common.databus.LiveDataBus;

import com.example.common.mvvm.BaseEntity;
import com.example.common.mvvm.DataActionEntity;
import com.example.common.mvvm.NetErroEntity;
import com.example.common.mvvm.model.BaseRepository;

import java.lang.reflect.ParameterizedType;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BaseViewModel <M extends BaseRepository> extends ViewModel
        implements IViewModel ,Observer<BaseEntity> {
    private CompositeDisposable compositeDisposable;
    protected M repository;//负责全部网络请求

    public BaseViewModel(){
        compositeDisposable = new CompositeDisposable();
        initRespository();
    }

    private void initRespository(){
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class clazz = (Class) type.getActualTypeArguments()[0];
        try {
            repository = (M) clazz.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public abstract void onResult(BaseEntity entity);

    protected abstract void initData();
    @Override
    public void onCreate() {
        initData();
    }
    @Override
    public void onDestroy() {
        //统一解除rxjava订阅
        compositeDisposable.dispose();
        compositeDisposable.clear();
    }
    //显示dialog
    protected void showDialog(){
    }
    //关闭dialog
    protected void hideDialog(){
    }
    @Override
    public void onSubscribe(@NonNull Disposable d) {
        //统一保存订阅记录
        compositeDisposable.add(d);
        showDialog();
    }
    @Override
    public void onNext(@NonNull BaseEntity baseEntity) {
        if (baseEntity instanceof NetErroEntity){
            NetErroEntity netErroEntity = (NetErroEntity) baseEntity;
            ToastUtils.showShort(netErroEntity.message);
            return;
        }
        onResult(baseEntity);
    }
    @Override
    public void onError(@NonNull Throwable e) {
        LogUtils.e("onError:"+e.getMessage());
        ToastUtils.showShort("请求错误"+e);
    }
    @Override
    public void onComplete() {
        hideDialog();
    }

}
